/*
 * @Descripttion: 
 * @version: 
 * @Author: TT
 * @Date: 2023-10-20 18:14:38
 * @LastEditors: TT
 * @LastEditTime: 2023-10-20 18:14:39
 */
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import '../config/data_config/data_config_index.dart';
import '../utils/utils_index.dart';
import '../base_ui_config/common_state.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({Key? key}) : super(key: key);

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends CommonState<WebViewPage> {
  late String initialUrl;

  late String title = "";

  late WebViewController webViewController;
  int webProgress = 0;

  @override
  void initState() {
    super.initState();
    initialUrl = currentGetArguments();
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    webViewController = WebViewController.fromPlatformCreationParams(params)
      ..loadRequest(Uri.parse(initialUrl));
  }

  @override
  interfaceRenderingCompleted() {
    webViewController.setNavigationDelegate(NavigationDelegate(
      onProgress: (progress) {
        setState(() {
          webProgress = progress;
        });
        webViewController.getTitle().then((value) {
          setState(() {
            title = value ?? "";
          });
        });
      },
      onPageFinished: (url) {},
    ));
  }

  @override
  String? createAppBarTitleStr() {
    return title;
  }

  @override
  Widget createBody({
    required BuildContext context,
    BoxConstraints? constraints,
  }) {
    Widget body = Column(
      children: [
        configLineearProgressIndicatorWidget(),
        configWebView(),
      ],
    );
    return body;
  }

  @override
  configleadingCallbak({BuildContext? context}) async {
    if (await webViewController.canGoBack()) {
      webViewController.goBack();
    } else {
      currentGoback();
    }
  }

  configWebView() {
    Widget body = WebViewWidget(
      controller: webViewController,
    );
    body = Expanded(child: body);
    return body;
  }

  /// 创建进度条
  configLineearProgressIndicatorWidget() {
    Widget body = LinearProgressIndicator(
      backgroundColor: HzyCommonColor().backgroudgrey,
      valueColor: const AlwaysStoppedAnimation(Colors.red),
      minHeight: 2,
      value: webProgress / 100.00,
    );

    body = Offstage(
      offstage: webProgress == 100,
      child: body,
    );
    return body;
  }
}
